package com.wontube.core.plugin;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wontube.client.modle.vo.ClientSession;
import com.wontube.core.annotation.NoLoginSupport;
import com.wontube.core.plugin.IPlugin;
import com.wontube.core.pub.IUserInfo;
import com.wontube.core.pub.ServerContext;
import com.wontube.core.remote.IHandler;

/**
 * 
 * @author yuechao
 * 
 *         校验用户是否已经登录的插件
 */
public class ValidateLoginPlugin implements IPlugin {
	private final static Logger logger = LoggerFactory.getLogger(ValidateLoginPlugin.class);
	
	/**
	 * 获取优先级。值越小，越先执行
	 * 
	 * @return
	 */
	@Override
	public float getPriority() {
		return 0f;
	}

	/**
	 * 处理请求前执行某些动作
	 * 
	 * @param context
	 * @param request
	 * @throws Exception
	 */
	@Override
	public boolean begin(IHandler handler) throws Exception {
		ServerContext context = handler.getContext();
		boolean isNoNeedLogin = handler.getClass().isAnnotationPresent(NoLoginSupport.class);
		if (!isNoNeedLogin) {
			isNoNeedLogin = context.getMethodWrapper().getMethod().isAnnotationPresent(NoLoginSupport.class);
		}

		if (isNoNeedLogin) {
			return true;
		}
		
		ClientSession session = context.getSession();
		IUserInfo user = (IUserInfo)session.getProperty("user");
		if (user == null) {
			context.error("server error：session experied, please login first.");
			logger.debug("session experied, please login first.");
			return false;
		}

		return true;
	}

	/**
	 * 处理请求成功后执行某些动作
	 * 
	 * @param context
	 * @param request
	 * @throws Exception
	 */
	@Override
	public void commit(IHandler handler) throws Exception {
		// do nothing
	}

	/**
	 * 处理请求后执行某些动作
	 * 
	 * @param context
	 * @param request
	 */
	@Override
	public void end(IHandler handler) {
		// do nothing
	}
}
